﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using SharpCompress.Common;
using SharpCompress.Reader;
using System.IO;

/// <summary>
/// Summary description for CompressHelper
/// </summary>
/// 
namespace SERP.Commons
{
    public class CompressHelper
    {
        public CompressHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static List<string> Read(string fileName, string destPath)
        {
            if (!Directory.Exists(destPath))
                Directory.CreateDirectory(destPath);
            string ext = Path.GetExtension(fileName).ToLower();
            switch (ext)
            {
                case ".rar":
                    return Read(fileName, destPath, CompressionType.Rar);
                    break;
                case ".gz":
                    return Read(fileName, destPath, CompressionType.GZip);
                    break;
                case ".zip":
                case ".bz2":
                    return Read(fileName, destPath, CompressionType.BZip2);
                    break;
            }
            return Read(fileName, destPath, CompressionType.Unknown);
        }
        public static List<string> Read(string fileName, string destPath, CompressionType expectedCompression)
        {
            List<string> lsFiles = new List<string>();

            if (!Directory.Exists(destPath))
                Directory.CreateDirectory(destPath);
            Read(new string[] { fileName }, lsFiles, destPath, expectedCompression);
            return lsFiles;
        }

        public static void Read(IEnumerable<string> testArchives, List<string> lsFiles, string destPath, CompressionType expectedCompression)
        {
            foreach (var path in testArchives)
            {
                using (Stream stream = File.OpenRead(path))
                using (IReader reader = ReaderFactory.Open(stream, Options.None))
                {
                    UseReader(reader, lsFiles, destPath, expectedCompression);
                }
            }
        }

        public static void UseReader(IReader reader, List<string> lsFiles, string destPath, CompressionType expectedCompression)
        {

            while (reader.MoveToNextEntry())
            {
                if (!reader.Entry.IsDirectory)
                {
                    reader.WriteEntryToDirectory(destPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                    lsFiles.Add(reader.Entry.FilePath);
                }
            }
        }
    }
}